<template>
  <div class="course-arrangement-container">
    <div class="header">
      <h1>学员课程信息</h1>
    </div>
    
    <div class="content">
      <div class="sidebar">
        <div class="status-card">
          <h3>预约状态</h3>
          <div class="status-item success">
            <span class="status-icon">✓</span>
            <span class="status-text">已确认</span>
          </div>
        </div>
        
        <div class="coach-info-card">
          <h3>教练信息</h3>
          <div class="coach-details">
            <div class="coach-avatar">
              <div class="avatar-placeholder">教练</div>
            </div>
            <div class="coach-data">
              <p class="coach-name">{{ coachInfo.coachName || '王教练' }}</p>
              <p class="coach-title">高级驾驶教练</p>
              <p class="coach-contact">联系电话: {{ coachInfo.coachPhone || '138 **** 5678' }}</p>
              <p class="coach-experience">教龄: {{ coachInfo.experience || '8年' }}</p>
            </div>
          </div>
        </div>
      </div>
      
      <div class="main-content">
        <div class="student-info-section">
          <h3>个人信息</h3>
          <div class="info-form">
            <div class="form-group">
              <label>学员姓名</label>
              <input type="text" v-model="studentInfo.studentName" placeholder="请输入姓名" disabled>
            </div>
            <div class="form-group">
              <label>联系方式</label>
              <input type="text" v-model="studentInfo.studentPhone" placeholder="请输入手机号码" disabled>
            </div>
          </div>
        </div>
        
        <div class="progress-section">
          <h3>课程进度</h3>
          <div class="progress-bars">
            <div class="progress-item">
              <div class="progress-label">
                <span>科目一</span>
                <span class="status">已完成</span>
              </div>
              <div class="progress-bar">
                <div class="progress-fill complete"></div>
              </div>
            </div>
            
            <div class="progress-item">
              <div class="progress-label">
                <span>科目二</span>
                <span class="status">学习中</span>
              </div>
              <div class="progress-bar">
                <div class="progress-fill in-progress" style="width: 60%"></div>
              </div>
            </div>
            
            <div class="progress-item">
              <div class="progress-label">
                <span>科目三</span>
                <span class="status">未开始</span>
              </div>
              <div class="progress-bar">
                <div class="progress-fill not-started"></div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="arrangement-section">
          <h3>训练安排</h3>
          <div class="arrangement-form">
            <div class="form-group">
              <label>训练科目</label>
              <select v-model="arrangement.courseId">
                <option v-for="course in courses" :key="course.courseId" :value="course.courseId">
                  {{ course.courseName }}
                </option>
              </select>
            </div>
            
            <div class="form-group">
              <label>训练日期</label>
              <input type="date" v-model="arrangement.date">
            </div>
            
            <div class="form-group">
              <label>时间段</label>
              <div class="time-select">
                <input type="time" v-model="arrangement.startTime"> - 
                <input type="time" v-model="arrangement.endTime">
              </div>
            </div>
            
            <div class="action-buttons">
              <button class="submit-btn" @click="submitArrangement">提交预约</button>
              <button class="reset-btn" @click="resetForm">重置信息</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const studentId = ref(route.params.studentId);

// 初始化为空对象，介绍只保留ID
const studentInfo = ref({
  studentId: studentId.value,
  studentName: '',
  studentPhone: '',
});

// 初始化为空对象，将从后端获取真实数据
const coachInfo = ref({
  coachName: '',
  coachPhone: '',
  experience: ''
});

// 初始化为空数组，将从后端获取真实数据
const courses = ref([]);

const arrangement = ref({
  courseId: '',
  date: '',
  startTime: '15:00',
  endTime: '18:00'
});

onMounted(async () => {
  // 获取学生信息
  await fetchStudentInfo();
  // 获取可用课程列表
  await fetchCourses();
});

const fetchStudentInfo = async () => {
  try {
    // 从后端API获取学生信息
    const response = await axios.get(`/api/arrange/student/${studentId.value}`);
    console.log('获取学生详细信息:', response.data);
    
    // 提取学生数据，处理可能的嵌套结构
    let studentData = null;
    
    if (response.data) {
      // 检查数据是否在response.data.data中
      if (response.data.data) {
        studentData = response.data.data;
      } else {
        studentData = response.data;
      }
      
      // 提取学生信息，支持下划线和驼峰命名
      studentInfo.value = {
        studentId: studentData.student_id || studentData.studentId || studentId.value,
        studentName: studentData.student_name || studentData.studentName || '',
        studentPhone: studentData.student_phone || studentData.studentPhone || ''
      };
      
      // 提取教练信息
      coachInfo.value = {
        coachName: studentData.coach_name || studentData.coachName || '',
        coachPhone: studentData.coach_phone || studentData.coachPhone || '',
        experience: studentData.experience || ''
      };
      
      console.log('处理后的学生信息:', studentInfo.value);
      console.log('处理后的教练信息:', coachInfo.value);
    }
  } catch (error) {
    console.error('获取学生信息失败:', error);
    // 错误时统一使用空值，不使用模拟数据
    studentInfo.value = {
      studentId: studentId.value,
      studentName: '',
      studentPhone: ''
    };
    
    coachInfo.value = {
      coachName: '',
      coachPhone: '',
      experience: ''
    };
  }
};

const fetchCourses = async () => {
  try {
    // 从后端API获取课程列表
    const response = await axios.get('/api/arrange/courses');
    console.log('获取课程列表:', response.data);
    
    // 提取课程数组
    let courseArray = [];
    
    if (response.data) {
      // 检查数据是否在response.data.data中
      if (Array.isArray(response.data)) {
        courseArray = response.data;
      } else if (response.data.data && Array.isArray(response.data.data)) {
        courseArray = response.data.data;
      } else if (typeof response.data === 'object' && !Array.isArray(response.data)) {
        // 单个课程对象
        courseArray = [response.data];
      }
      
      if (courseArray.length > 0) {
        // 处理课程数据格式
        courses.value = courseArray.map(course => ({
          courseId: course.course_id || course.courseId,
          courseName: course.course_name || course.courseName || `科目${course.course_id || course.courseId}`
        }));
        console.log('处理后的课程数据:', courses.value);
      } else {
        courses.value = [];
      }
    } else {
      courses.value = [];
    }
  } catch (error) {
    console.error('获取课程列表失败:', error);
    // 错误时使用空数组，不使用模拟课程列表
    courses.value = [];
  }
};

const submitArrangement = async () => {
  if (!arrangement.value.courseId || !arrangement.value.date) {
    alert('请选择训练科目和日期');
    return;
  }
  
  try {
    // 调用后端API安排课程
    const response = await axios.post('/api/arrange/course', {
      studentId: studentId.value,
      courseId: arrangement.value.courseId
    });
    
    console.log('课程安排响应:', response.data);
    
    // 不管后端是否成功存储，我们都在浏览器中保存安排信息
    // 获取当前选中的课程名称
    const selectedCourse = courses.value.find(course => course.courseId == arrangement.value.courseId);
    const courseName = selectedCourse ? selectedCourse.courseName : `科目${arrangement.value.courseId}`;
    
    // 创建安排信息对象
    const arrangementInfo = {
      studentId: studentId.value,
      studentName: studentInfo.value.studentName,
      studentPhone: studentInfo.value.studentPhone,
      courseId: arrangement.value.courseId,
      courseName: courseName,
      coachName: coachInfo.value.coachName,
      coachPhone: coachInfo.value.coachPhone,
      date: arrangement.value.date,
      startTime: arrangement.value.startTime,
      endTime: arrangement.value.endTime,
      timestamp: new Date().getTime()
    };
    
    // 将安排信息存储到localStorage
    // 先获取现有的安排数据
    const existingArrangements = JSON.parse(localStorage.getItem('courseArrangements') || '{}');
    
    // 将新的安排信息添加到学生的安排列表中
    if (!existingArrangements[studentId.value]) {
      existingArrangements[studentId.value] = [];
    }
    
    // 将新安排添加到数组开头，这样最新的安排在前面
    existingArrangements[studentId.value].unshift(arrangementInfo);
    
    // 保存回本地存储
    localStorage.setItem('courseArrangements', JSON.stringify(existingArrangements));
    
    if (response.data) {
      alert('课程安排成功');
      // 返回学生管理页面
      router.push('/student-management');
    }
  } catch (error) {
    console.error('课程安排失败:', error);
    alert('课程安排失败，请稍后重试');
  }
};

const resetForm = () => {
  arrangement.value = {
    courseId: '',
    date: '',
    startTime: '15:00',
    endTime: '18:00'
  };
};
</script>

<style scoped>
.course-arrangement-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

h1, h3 {
  color: #333;
  margin-top: 0;
}

.content {
  display: flex;
  gap: 20px;
}

.sidebar {
  width: 300px;
  flex-shrink: 0;
}

.main-content {
  flex-grow: 1;
}

.status-card, .coach-info-card, .student-info-section, .progress-section, .arrangement-section {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.status-item {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.status-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin-right: 10px;
}

.success .status-icon {
  background-color: #4CAF50;
  color: white;
}

.coach-details {
  display: flex;
  margin-top: 15px;
}

.coach-avatar {
  width: 50px;
  height: 50px;
  margin-right: 15px;
}

.coach-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #007bff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
}

.coach-data p {
  margin: 5px 0;
}

.coach-name {
  font-weight: bold;
  font-size: 16px;
}

.coach-title {
  color: #666;
  font-size: 14px;
}

.coach-contact, .coach-experience {
  color: #888;
  font-size: 13px;
}

.info-form, .arrangement-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #555;
}

input, select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

input:disabled {
  background-color: #f9f9f9;
}

.time-select {
  display: flex;
  align-items: center;
}

.time-select input {
  width: 45%;
}

.progress-bars {
  margin-top: 15px;
}

.progress-item {
  margin-bottom: 15px;
}

.progress-label {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.status {
  font-size: 12px;
}

.complete + .status {
  color: #4CAF50;
}

.in-progress + .status {
  color: #2196F3;
}

.not-started + .status {
  color: #9E9E9E;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: #eee;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 4px;
}

.complete {
  width: 100%;
  background-color: #4CAF50;
}

.in-progress {
  background-color: #2196F3;
}

.not-started {
  width: 0;
  background-color: #9E9E9E;
}

.action-buttons {
  grid-column: 1 / 3;
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.submit-btn, .reset-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
}

.submit-btn {
  background-color: #007bff;
  color: white;
}

.reset-btn {
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  color: #333;
}

.submit-btn:hover {
  background-color: #0069d9;
}

.reset-btn:hover {
  background-color: #e2e6ea;
}
</style>
